<?php
/**
 * Created by PhpStorm.
 * User: CYJiao
 * Date: 6/1/15
 * Time: 09:50
 */


class SiteController extends Controller
{

	/**
	 * Method returning filters array.
	 */
    public function filters()
    {
        return array(
            'accessControl',//Performs access control for CRUD operations
        );
    }

    /**
     * Defines User Access Level.
     */
     public function accessRules()
     {
         return array(
             array('allow',
                 'actions'=>array(),//Actions allowed
                 'roles'=>array('@'),//Roles allowed to perform actions
             ),
             array('deny',
                 'actions'=>array(),//Actions not allowed
                 'roles'=>array('*'),//Roles not allowed to perform actions
             ),
         );
     }

	/**
	 * Declares class-based actions.
	 */
	public function actions(){
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'height'=>37,
				'minLength'=>4,
				'maxLength'=>6,
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the Register Page used to new user register.
     * If the user has logged in, then redirect to dashboard.
	 */
	public function actionRegister()
	{  
		// If the user is still logged then redirect to dashboard
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged')
        {
            $this->redirect(array('dashboard'));// View redirection
            return;
        }
        else  // If is not logged
        {
			$RegisterForm = new RegisterForm;

			// if it is ajax validation request
			if(isset($_POST['ajax']) && $_POST['ajax']==='register-form'){
				echo CActiveForm::validate($RegisterForm);
				Yii::app()->end();
			}

			// collect user input data
			if(isset($_POST['RegisterForm'])){
				$RegisterForm->attributes=$_POST['RegisterForm'];
				// validate user input and redirect to the previous page if valid
				if($RegisterForm->validate() && $RegisterForm->login()){
					$this->redirect(array('dashboard'));
				}
			}
			$this->layout='login';
			$this->render('register', array('registerForm'=>$RegisterForm));
		}
	}

	/**
	 * This is the action to handle external exceptions.
     * This error will be show in the page.
	 */
	public function actionError()
	{
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				//echo '产品正在维护中，请耐心等待...';
				echo $error['message']; // use to show the error message
			else
				echo $error['message'];
		}
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin(){

		// If the user is still logged, then redirect to dashboard
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged')
        {
            $this->redirect(array('dashboard'));// View redirection
            return;
        }
        else  //If is not logged
        {
			$loginForm = new LoginForm;

			// if it is ajax validation request
			if(isset($_POST['ajax']) && $_POST['ajax']==='login-form'){
				echo CActiveForm::validate($loginForm);
				Yii::app()->end();
			}

			// collect and validate the user input data
			if(isset($_POST['LoginForm'])){
				$loginForm->attributes=$_POST['LoginForm'];
				// validate user input and redirect to the previous page if valid
				if($loginForm->validate() && $loginForm->login()){

                    // $log = new Log600100(); //Create new empty record
                    // $log->action = 'login_seccess';//Saving the action type
                    // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                    // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                    // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                    // $log->target = '';//针对对象
                    // $log->save(false);//Saving the entire record with validation

					$this->redirect(array('dashboard'));
				}else{
                    // $log = new Log600100(); //Create new empty record
                    // $log->action = 'login_faile';//Saving the action type
                    // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                    // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                    // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                    // $log->target = '';//针对对象
                    // $log->save(false);//Saving the entire record with validation
                }
			}
			$this->layout='login';
			$this->render('login', array('loginForm'=>$loginForm));
		}
	}

    /**
     * Displays the Dashboard Page
     * This is the main page of the system
     */
    public function actionDashboard(){

        //If the user is still logged I redirect him to dashboard
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->layout = 'main'; // default layout is main
            $this->render('dashboard');
        }else
            $this->redirect(array('site/login'));// View redirection
    }

	/**
	 * Logs out the current user and redirect to login.
	 */
	public function actionLogout(){

		Yii::app()->user->logout();

        // $log = new Log600100(); //Create new empty record
        // $log->action = 'login_out';//Saving the action type
        // $log->create_time = new CDbExpression('NOW()');//Saving date and time
        // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
        // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
        // $log->target = '';//针对对象
        // $log->save(false);//Saving the entire record with validation

		$this->redirect(Yii::app()->homeUrl);
	}


    /******************************************************************************************
     * Following functions are the layout of the main panel
     ******************************************************************************************/

    /**
     * Getting dashboard header
     */
    public function actionGetHeader(){

        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

            // doctor information
            $doctorInfo = TblDoctorInformation::model()->findByAttributes(array('pk_fk_doctor_id'=>Yii::app()->session['id']));



            // get doctor head picture in scaling 180*180 with doctor information
            $url = 'http://picserver.o2omedical.com:8080/o2o_pic_server'.$doctorInfo['doctor_file_url'].'scaling/'.$doctorInfo['doctor_file_id'].'_180_180'.$doctorInfo['doctor_file_suffix'].'?token=b226d434-052a-4a14-9c59-917173a12864';

            // add patient url
            $addPatient='http://fg.o2omedical.com/views/register/patientRegister.jsp?referrer_name='.Yii::app()->session['username'];
            // add doctor url
            $addDoctor='http://fg.o2omedical.com/views/register/doctorRegister.jsp?referrer_name='.Yii::app()->session['username'];
            // add delegate url
            $addDelegate='http://fg.o2omedical.com/views/register/delegateRegister.jsp?referrer_name='.Yii::app()->session['username'];

            $this->render('header',
                array(
                    'doctorInfo'=>$doctorInfo,
                    'url'=>$url,
                    'role'=>'',
                    'addPatient'=>$addPatient,
                    'addDoctor'=>$addDoctor,
                    'addDelegate'=>$addDelegate
                )
            );
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Getting dashboard left-side
     */
    public function actionGetNavigation(){

        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

            // add patient url
            $addPatient='http://www.brglxt.com/OnlineAccountManagement/views/register/patientRegister.jsp?referrer_name='.Yii::app()->session['username'];

            $this->render('navigation',
                array(
                    'addPatient'=>$addPatient
                ));
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Getting dashboard footer
     */
    public function actionGetFooter(){

        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('footer');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Getting dashboard center
     */
    public function actionGetCenter(){

        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {

            
            $list_new_pic = Yii::app()->db->createCommand("SELECT * from tbl_crm_news where pre_img !='' ORDER BY update_time DESC limit 0,3")->queryAll();

            $list_new_no_pic = Yii::app()->db->createCommand("SELECT * from tbl_crm_news where pre_img ='' ORDER BY update_time DESC limit 0,6")->queryAll();

            $list_ad = Yii::app()->db->createCommand("SELECT * from tbl_crm_ad ORDER BY ad_position")->queryAll();

            // $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            // $db = $conn->o2omongo;
            // $collection_doctor_articles = $db->selectCollection('cf_articles');
 
            // $cursor = $collection_doctor_articles->find()->sort(array('update_time' => -1))->limit(10);
            // $result = array();
            // $rows = array();
            // while ($cursor->hasNext()) {
            //     $rows = $cursor->getNext();
            //     $result[] = $rows;
            // }

            $this->render('center',array('list_new_pic'=>$list_new_pic,'list_new_no_pic'=>$list_new_no_pic,'list_ad'=>$list_ad));
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Getting dashboard main page content
     * @param bigint $pk_doctor_id - for pushing special information to the doctor
     */
    public function actionGetMainContent($pk_doctor_id){

        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            // $doctorInformation = TblDoctorInformation::model()->findByAttributes(array('pk_fk_doctor_id'=>$pk_doctor_id));
            $this->layout='main';
            $this->render('maincontent');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

}
